package com.mall.framework.util;

import com.mall.common.constant.CacheConstants;
import com.mall.framework.service.CacheService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * Token工具类
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class TokenUtil {

    private final CacheService cacheService;

    /**
     * 从请求头中提取Token
     * @param request HTTP请求
     * @return Token字符串
     */
    public String extractToken(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        return null;
    }

    /**
     * 检查Token是否有效
     * @param token JWT Token
     * @return 是否有效
     */
    public boolean isTokenValid(String token) {
        if (!StringUtils.hasText(token)) {
            return false;
        }
        
        // 检查是否在黑名单中
        if (cacheService.isTokenInBlacklist(token)) {
            log.warn("Token在黑名单中");
            return false;
        }
        
        return true;
    }

    /**
     * 获取Token剩余过期时间
     * @param userId 用户ID
     * @return 剩余过期时间（秒）
     */
    public long getTokenExpireTime(Long userId) {
        return cacheService.getTokenExpireTime(userId);
    }

    /**
     * 刷新Token过期时间
     * @param userId 用户ID
     */
    public void refreshTokenExpireTime(Long userId) {
        cacheService.refreshTokenExpireTime(userId, CacheConstants.TOKEN_EXPIRE_TIME);
    }

    /**
     * 强制用户下线（删除所有相关缓存）
     * @param userId 用户ID
     */
    public void forceUserOffline(Long userId) {
        cacheService.removeUserToken(userId);
        cacheService.removeUserInfo(userId);
        log.info("用户已被强制下线，用户ID: {}", userId);
    }
} 